<template>
  <div>
    <div v-if="isEditGame===false&&isLearnGame===false"   :style="{opacity: isBoss ? 0.2 : 1 }">
      <p class="firstLine">当前合集: {{collectName}}</p>
      <el-select v-model="searchOpening" placeholder="选择开局" size="mini"  filterable>
        <el-option
            v-for="item in selectOpeningList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-button class="firstLine" type="warning" size="mini" @click="addGame">新增</el-button>
      <el-button class="firstLine" type="primary" size="mini" @click="backCollectMenu">返回合集</el-button>

      <el-table :data="gameData" stripe  border :height="650">
        <el-table-column
            prop="index" :show-overflow-tooltip="true"
            type="index"
            label="序号"
            width="80">
        </el-table-column>
        <el-table-column
            prop="white" :show-overflow-tooltip="true"
            label="白方"
            width="200">
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true"
                         prop="black"
                         label="黑方"
                         width="200">
        </el-table-column>
        <el-table-column
                         prop="result"
                         label="结果"
                         width="80">
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true"
            prop="opening"
            label="开局"
            width="180">
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true"
                         prop="gameDate"
                         label="对局时间"
                         width="120">
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true"
                         prop="description"
                         label="简介"
                         width="50">
        </el-table-column>
        <el-table-column
            prop="createAt"
            label="更新时间"
            width="200">
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
        >
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="learnGame(scope.row)">学习</el-button>
            <el-button type="warning" size="mini" @click="editGame(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="float: right; margin: 5px 20px 5px 5px;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 50, 100]"
          :page-size="20"
          layout="total, sizes, prev, pager, next, jumper"
          :total="gameCount">
      </el-pagination>
    </div>
<!--    编辑棋局-->
    <div v-if="isEditGame===true">
      <el-row>
        <el-col :span="7">
          <el-form ref="gameForm" :model="gameInfo" :rules="gameRules" label-width="80px" size="mini" label-position="left" class="f-m-5">
            <el-form-item label="白方:" prop="white">
              <el-input v-model="gameInfo.white" style="width: 250px"></el-input>
            </el-form-item>
            <el-form-item label="黑方:" prop="black">
              <el-input v-model="gameInfo.black" style="width: 250px"></el-input>
            </el-form-item>
            <el-form-item label="结果:" prop="result">
              <el-radio v-model="gameInfo.result" label="1-0">1-0</el-radio>
              <el-radio v-model="gameInfo.result" label="0-1">0-1</el-radio>
              <el-radio v-model="gameInfo.result" label="1/2-1/2">1/2-1/2</el-radio>
            </el-form-item>
            <el-form-item label="对局时间:" prop="gameDate">
              <el-input v-model="gameInfo.gameDate" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item label="开局:" prop="opening">
              <el-select v-model="gameInfo.opening" placeholder="选择或者新增" size="mini" allow-create filterable>
                <el-option
                    v-for="item in openingList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="描述:" prop="description">
              <el-input v-model="gameInfo.description" style="width: 280px" type="textarea"  :autosize="{ minRows: 3, maxRows: 3}"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="7">
          <chessboard :onPromotion="promote" :orientation="boardColor" @onMove="getBoardInfo" :fen="currentFen"
                      :style="{opacity: isBoss ? 0.05 : 1 }"/>
        </el-col>
        <el-col :span="10">

          <el-table :data="gameInfo.gameData" border stripe  style="width: 100%" height="320px" :style="{opacity: isBoss ? 0.5 : 1 }"  >
            <el-table-column
                label="棋步"
                type="index"
                width="50">
            </el-table-column>
            <el-table-column
                prop="move"
                label="走法"
                width="100"
            >
            </el-table-column>
            <el-table-column
                prop="description.length"
                label="解读"
            >
            </el-table-column>
            <el-table-column
                fixed="right"
                width="150"
                label="操作"
            >
              <template slot-scope="scope">
                <el-button type="success" size="mini" @click="editGameData(scope.$index)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7">
          分支：
          <chessboard :onPromotion="promote" :orientation="boardColor" @onMove="getChildBoardInfo" :fen="childFen"
                      :style="{opacity: isBoss ? 0.05 : 1 }"/>
        </el-col>
        <el-col :span="10">
          <div :style="{opacity: isBoss ? 0.25 : 1 }">
            <el-button type="primary" size="mini" @click="addChild()" class="firstLine">添加分支</el-button>
            <el-button type="danger" size="mini" @click="deleteChild()" class="firstLine">删除分支</el-button>
            <el-button type="warning" size="mini" @click="undo()" class="firstLine">撤回</el-button>
            <el-button type="success" size="mini" @click="saveGame()" class="firstLine">保存</el-button>
            <el-button type="info" size="mini" @click="returnCollectList()" class="firstLine">返回</el-button>
            <el-popconfirm
                title="是否确定删除棋局"  style="margin-left: 10px"
            >
              <el-button slot="reference" @click="deleteGame" type="danger" size="mini">删除</el-button>
            </el-popconfirm>

            <el-button type="danger" size="mini" @click="isBoss=!isBoss" class="firstLine">老板键</el-button>
          </div>
          <el-table :data="childData || []" border stripe  style="width: 100%" height="300px" :style="{opacity: isBoss ? 0.5 : 1 }"  >
            <el-table-column
                label="分支"
                type="index"
                width="50">
            </el-table-column>
            <el-table-column
                prop="move"
                label="走法"
                width="100"
            >
            </el-table-column>
            <el-table-column  :show-overflow-tooltip="true"
                prop="description"
                label="解读"
                width="100"
            >
            </el-table-column>
            <el-table-column
                fixed="right"
                width="150"
                label="操作"
            >
              <template slot-scope="scope">
                <el-button type="success" size="mini" @click="editChildData(scope.$index)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
<!--        保存后的分支数据，只有走法-->
        <el-col :span="7">

          <el-table :data="childDataRes" border stripe  height="300px" :style="{opacity: isBoss ? 0.5 : 1 }"  style="margin-top: 36px;margin-left: 5px;">
            <el-table-column
                type="index"
                label="序号"
                width="50">
            </el-table-column>
            <el-table-column
                :show-overflow-tooltip="true"
                prop="move"
                label="分支"
            >
            </el-table-column>
            <el-table-column
                fixed="right"
                width="100"
                label="操作"
            >
              <template slot-scope="scope">
                <el-button type="success" size="mini" @click="removeChild(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
<!--    学习棋局-->
    <div v-if="isLearnGame===true"  >
      <el-row>
        <el-col :span="7">
          <chessboard :onPromotion="promote" :orientation="boardColor" @onMove="getLearnBoardInfo" :fen="learnFen"/>
        </el-col>
        <el-col :span="7">
          <el-table :data="moveHistory" border stripe
                    highlight-current-row :height="280"
                    @cell-click="handleSelectMove">
            <el-table-column
                type="index"
                label="步数"
                width="50">
            </el-table-column>
            <el-table-column
                prop="white"
                label="白方"
            >
            </el-table-column>
            <el-table-column
                prop="black"
                label="黑方"
            >
            </el-table-column>
          </el-table>
          <el-row>
            <el-tooltip class="item" effect="dark" content="翻转黑白朝向" placement="top">
              <el-button  type="info" icon="el-icon-refresh" style="margin:4px" size="small" @click="reverseBoard"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="回到最开始" placement="top">
              <el-button type="primary"  round icon="el-icon-d-arrow-left" style="margin:4px"  size="small" @click="jumpToBegin" :loading=autoLoading ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="后退一步" placement="top">
              <el-button  type="primary" round icon="el-icon-arrow-left" style="margin:4px"  size="small"  @click="jumpToBack" :loading=autoLoading></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="前进一步" placement="top">
              <el-button  type="primary" round icon="el-icon-arrow-right" style="margin:4px" size="small" @click="jumpToNext" :loading=autoLoading></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="跳转到末尾" placement="top">
              <el-button   type="primary" round icon="el-icon-d-arrow-right" style="margin:4px"  size="small" @click="jumpToEnd" :loading=autoLoading></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="自动播放" placement="top">
              <el-button type="warning" round icon="el-icon-caret-right" style="margin:4px"  size="small" :loading=autoLoading @click="autoMove"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="返回" placement="top">
              <el-button  type="danger" round style="margin:4px" size="small" icon="el-icon-circle-close" :loading=autoLoading @click="back2GameList"></el-button>
            </el-tooltip>
          </el-row>
        </el-col>
        <el-col :span="10">
        <div class="f-m-5" >
          <el-descriptions title="对局信息" :column="1" size="medium">
            <el-descriptions-item label="白方">{{ learnGameInfo.white }}</el-descriptions-item>
            <el-descriptions-item label="黑方">{{ learnGameInfo.black }}</el-descriptions-item>
            <el-descriptions-item label="结果">{{ learnGameInfo.result }}</el-descriptions-item>
            <el-descriptions-item label="开局">{{ learnGameInfo.opening }}</el-descriptions-item>
            <el-descriptions-item label="对局时间">{{ learnGameInfo.gameDate }}</el-descriptions-item>
          </el-descriptions>
          <el-input type="textarea" readonly v-model="learnGameInfo.description" :autosize="{ minRows: 4, maxRows: 4}"
                    resize="false" class="textarea"></el-input>
        </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span=7>
          <h5>解读:</h5>
          <el-input type="textarea" readonly v-model="currentDescription" :autosize="{ minRows: 4, maxRows: 4}"
                    resize="false" class="textarea"></el-input>
        </el-col>
        <el-col :span=17>
          <el-table :data="learnChildData" border stripe
                    highlight-current-row :height="350">
            <el-table-column
                type="index"
                label="序号"
                width="50">
            </el-table-column>
            <el-table-column
                prop="text"
                label="分支走法"
            >
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="100"
            >
              <template slot-scope="scope">
<!--                根据状态变更按钮的名称，选择和返回-->
                <el-button :type="scope.row.btnType" size="mini" @click="chooseChild(scope.row, scope.$index)">{{ scope.row.btnName }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

    </div>
    <el-dialog
        :visible.sync="editManageModal"
        title="增加描述"
        width="800px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <p class="f-m-5">描述: </p> <el-input class="f-m-5" type="textarea" :autosize="{ minRows: 5}"  v-model="description"></el-input>
      <el-button @click="editManageModal = false" size="mini">取消</el-button>
      <el-button type="primary" @click="updateSingleManageGameData" size="mini" >确定</el-button>
    </el-dialog>
<!--    分支的描述-->
    <el-dialog
        :visible.sync="editChildModal"
        title="增加描述"
        width="800px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <p class="f-m-5">描述: </p> <el-input class="f-m-5" type="textarea" :autosize="{ minRows: 5}"  v-model="description"></el-input>
      <el-button @click="editChildModal = false" size="mini">取消</el-button>
      <el-button type="primary" @click="updateSingleManageData" size="mini" >确定</el-button>
    </el-dialog>
  </div>
</template>

<script>

import emitvue from "@/lib/emitvue";
import Database from "@/lib/database";
import * as utils from "@/lib/utils";
import {chessboard} from 'vue-chessboard'
import {checkIllegalText, invoke, parseFenDropHistory, sleep} from "@/lib/utils";
import chessmate from "@/lib/chessmate";
import {clipboard} from "electron";

export default {
  name: "Game",
  data() {
    return {
      isDev: false,
      gameData: [],
      editIndex: 0,
      // 编辑棋局部分
      isEditGame: false,
      // 填入的开局和名称
      openingList: [],
      selectOpeningList: [],
      isBoss: false,
      // 编辑棋局
      currentFen: utils.newGame,
      gameInfo: {
        white: '',
        black: '',
        result: '',
        opening: '',
        description: '',
        gameDate: '',
        gameData: [], // move, description, children[move, description]
      },
      gameRules: {
        white: [
          { required: true, message: '请输入白方名字', trigger: 'blur' }
        ],
        black: [
          { required: true, message: '请输入黑方名字', trigger: 'blur' }
        ],
        result: [
          { required: true, message: '请选择结果', trigger: 'blur' }
        ],
        opening: [
          { required: true, message: '请选择开局', trigger: 'blur' }
        ],
      },
      boardColor: 'white',
      editManageModal: false, // 描述框
      editChildModal: false, // 描述框
      description: '', //描述
      childFen: utils.newGame, //  永远比当前局面差一步，用来创建分支变例
      tempFen: utils.newGame, // 为了创建多个child来准备的
      childData: [],
      childDataRes: [],
      // 根据sortCode来判断更新的棋局
      editSortCode: null,
      // 学习模块
      isLearnGame: false,
      learnFen: utils.newGame,
      // 为了防止用户自行落子
      tempLearnFen: utils.newGame,
      // 棋局的信息
      learnGameInfo: {},
      moveNum: -1,
      // 记录白方黑方落子
      moveHistory: [],
      moveData: [], // 按顺序记录落子，fen，分支数据
      // 学习的数据
      learnData: [],
      autoLoading: false,
      currentDescription: '',
      learnChildData: [],
      // 是否在选择分支
      isEnterChild: false,
      childMoveNum: 0,
      tempMoveNum: 0,
      // 进入分支之前的备份Fen
      tempGameFen: utils.newGame,
      // 记录了分支的对应走法
      childMoveData: [],

      gameCount: 0,
      // 页码和大小
      currentPage: 1,
      currentSize: 20,
      searchOpening: ''
    }
  },
  props: {
    hashName: {
      type: String,
    },
    collectName: {
      type: String,
    },
  },
  methods: {
    backCollectMenu() {
      emitvue.$emit('backCollect', null)
    },
    async getGameList(opening=null) {
      const {count, data} = await Database.getGameList(this.hashName, opening, this.currentSize, (this.currentPage - 1) * this.currentSize)
      this.gameData = data
      this.gameCount = count[0].count
      // 把16进制数据转字符串
      for (const game of this.gameData) {
        game.data = utils.hex2str(game.data)
        game.data = JSON.parse(game.data)
      }
      console.log("this.gameCount", this.gameCount)
    },
    async getOpeningSort() {
      this.openingList = []
      const group = await Database.getOpeningGroup()
      for (const item of group) {
        this.openingList.push({label: item.name, value: item.name})
      }
    },
    async getOpeningDistinct() {
      this.selectOpeningList = []
      const group = await Database.getGameOpeningDistinct(this.hashName)
      console.log("group", group)
      for (const item of group) {
        this.selectOpeningList.push({label: item.opening, value: item.opening})
      }
    },
    // 升变
    promote() {
      if (confirm("是否升变为后？")) {
        return 'q'
      } else {
        if (confirm("是否升变为车？")) {
          return 'r'
        } else {
          if (confirm("是否升变为马？")) {
            return 'n'
          } else {
            if (confirm("是否升变为象？")) {
              return 'b'
            }
          }
        }
      }
      return 'q'
    },
    async getBoardInfo(data) {
      if (data.history.length === 0) return
      this.gameInfo.gameData.push({move: data.history[data.history.length - 1], description: '', childData: []})
      this.childFen = this.currentFen
      this.tempFen = this.childFen
      this.currentFen = data.fen
      this.childDataRes = []
    },
    async getChildBoardInfo(data) {
      if (data.history.length === 0) return
      this.childFen = data.fen
      if (!this.gameInfo.gameData.length) {
        await sleep(100)
        this.childFen = data.fen
        await sleep(100)
        this.childFen = utils.newGame
        await sleep(100)
        return this.$notify({duration: 1000, title: '通知', message: `初始局面不允许创建分支`, type: 'warning'})
      }
      this.childData.push({move: data.history[data.history.length - 1], description: ''})
    },
    editGameData(index) {
      this.editManageModal = true
      this.editIndex = index
      this.description = this.gameInfo.gameData[this.editIndex].description
    },
    editChildData(index) {
      this.editChildModal = true
      this.editIndex = index
      this.description = this.childData[index].description
    },
    updateSingleManageGameData() {
      if (checkIllegalText(this.description)) {
        return this.$notify({duration: 1000, title: '通知', message: `描述不允许包含特殊符号`, type: 'warning'})
      }
      this.gameInfo.gameData[this.editIndex].description = this.description
      this.editIndex = 0
      this.editManageModal = false
      this.description = ''
    },
    updateSingleManageData() {
      if (checkIllegalText(this.description)) {
        return this.$notify({duration: 1000, title: '通知', message: `描述不允许包含特殊符号`, type: 'warning'})
      }
      this.childData[this.editIndex].description = this.description
      this.editIndex = 0
      this.editChildModal = false
      this.description = ''
    },
    // 添加变例
    addChild() {
      if (!this.gameInfo.gameData[this.gameInfo.gameData.length - 1]) return this.$notify({duration: 1000, title: '通知', message: `初始局面不允许添加变例`, type: 'warning'})
      if (!this.childData.length) return this.$notify({duration: 1000, title: '通知', message: `请先创建分支`, type: 'warning'})
      this.gameInfo.gameData[this.gameInfo.gameData.length - 1].childData.push({data: this.childData})
      let text = ''
      for (const item of this.childData) {
        text += item.move + ' '
      }
      this.childDataRes.push({move: text})
      this.childData = []
      this.childFen = this.tempFen
    },
    deleteChild() {
      this.childData = []
      this.$notify({duration: 1000, title: '通知', message: `清空成功`, type: 'success'})
    },

    // 删除变例
    removeChild(index) {
      this.childDataRes.splice(index, 1)
      this.gameInfo.gameData[this.gameInfo.gameData.length - 1].childData.splice(index, 1)
    },
    async saveGame() {
      const res = await this.$refs['gameForm'].validate();
      if (!res) return
      console.log("this.gameInfo", this.gameInfo)
      await Database.saveGame(this.hashName, this.gameInfo, this.editSortCode)
      this.isEditGame = false
      this.editSortCode = null
      this.$notify({duration: 1000, title: '通知', message: `编辑成功`, type: 'success'})
      await sleep(200)
      this.clearGameData()
      await this.getGameList()
    },
    clearGameData() {
      this.gameInfo = {
        white: '',
        black: '',
        result: '',
        opening: '',
        description: '',
        gameDate: '',
        gameData: [], // move, description, children[move, description]
      }
      this.moveHistory = []
      this.gameData = []
      this.moveData = []
      this.childDataRes = []
      this.childData = []
    },
    async returnCollectList() {
      this.isEditGame = false
      await this.getGameList()
    },
    async undo() {
      if (!this.gameInfo.gameData.length) return this.$notify({duration: 1000, title: '通知', message: `已经到棋局的开始了`, type: 'warning'})
      this.gameInfo.gameData.pop()
      this.childDataRes = []
      // 这里需要重新计算上个节点是否有后续
      console.log("this.gameInfo.gameData", this.gameInfo.gameData)
      // 以这个为基准慢慢往后遍历 重新获取fen
      let targetFen = utils.newGame
      for (const data of this.gameInfo.gameData) {
        const move = data.move
        this.childFen = targetFen
        targetFen = chessmate.move(targetFen, move)
        this.currentFen = targetFen
      }
      // 警告：前面刚pop过，这里需要判断是否存在数组的length
      if (!this.gameInfo.gameData.length) return
      // 如果存在分支，则需要展示分支列表
      if (this.gameInfo.gameData[this.gameInfo.gameData.length - 1].childData.length) {
        const childData = this.gameInfo.gameData[this.gameInfo.gameData.length - 1].childData
        console.log("childData", childData)
        for (const child of childData) {
          const data = child.data
          let text = ''
          for (const item of data) {
            text += item.move + ' '
          }
          this.childDataRes.push({move: text})
        }
      }

    },
    // 新增棋局，先初始化一些数据
    addGame() {
      this.isEditGame = true
      this.gameInfo.gameData = []
      this.currentFen = utils.newGame
      this.clearGameData()
    },
    async editGame(data) {
      console.log("data", data)
      this.isEditGame = true
      this.editSortCode = data.sortCode
      const {white, black, description, gameDate, hashName, opening, result} = data
      this.gameInfo = {white, black, description, gameDate, hashName, opening, result}
      this.gameInfo.gameData = data.data
      this.currentFen = utils.newGame
      for (const data of this.gameInfo.gameData) {
        const move = data.move
        this.tempFen = this.currentFen
        this.currentFen = chessmate.move(this.currentFen, move)
      }
      if (this.gameInfo.gameData.length) {
        if (this.gameInfo.gameData[this.gameInfo.gameData.length - 1].childData.length) {
          for (const child of this.gameInfo.gameData[this.gameInfo.gameData.length - 1].childData) {
            const data = child.data
            let text = ''
            for (const item of data) {
              text += item.move + ' '
            }
            this.childDataRes.push({move: text})
          }
        }
      }
    },
    async handleCurrentChange(data) {
      if (this.currentPage === data) return
      this.currentPage = data
      await this.getGameList()
    },
    async handleSizeChange(data) {
      if (this.currentSize === data) return
      this.currentSize = data
      await this.getGameList()
    },
    async deleteGame() {
      if (!this.editSortCode) return this.$notify({duration: 1000, title: '通知', message: `编辑模式才可以删除棋局`, type: 'warning'})
      if (confirm("是否删除棋局？")) {
        await Database.deleteGame(this.editSortCode)
        this.isEditGame = false
        this.editSortCode = null
        await this.getGameList()
      }
    },
    // 学习开局
    async learnGame(gameData) {
      this.isLearnGame = true
      this.moveNum = -1
      console.log("data", gameData)
      const {white, black, description, gameDate, opening, result, data} = gameData
      this.learnGameInfo = {white, black, description, gameDate, opening, result}
      this.parseMove2History(data)
      this.$notify({duration: 1000, title: '通知', message: "每一步的fen将动态复制到剪切板，可以在分析模块进行分析", type: 'success'})
    },
    async getLearnBoardInfo(data) {
      console.log("data", data)
      this.learnFen = parseFenDropHistory(data.fen)
      if (data.history?.length) {
        this.$notify({duration: 1000, title: '通知', message: "本模块只允许观看对局", type: 'warning'})
        // TODO 直接赋值上一步的tempFen不起作用 只能这样
        this.moveNum--
        this.moveNum++
        this.moveNum++
      }
    },
    // TODO 支持选择某一列然后跳转棋谱
    handleSelectMove(row, column, cell, event) {
      console.log("column",column);
      console.log("row",row);
      console.log("11111", 11111)
    },
    // 将走法解析成历史记录
    parseMove2History(data) {
      console.log("data", data)
      this.moveHistory = [];
      this.moveList = []
      let black = [];
      let white = [];
      let tempFen = utils.newGame
      // 先把黑白分开
      for (let i = 0; i < data.length; i++) {
        tempFen = chessmate.move(tempFen, data[i].move)
        this.moveList.push({
          move: data[i].move,
          description: data[i].description,
          childData: data[i].childData,
          fen: tempFen
        })
        if (i % 2 === 0) {
          white.push({move: data[i].move});
        } else {
          black.push({move: data[i].move})
        }

      }
      for (let i = 0; i < white.length; i++) {
        let list = {
          index: i + 1,
          white: white[i].move,
          // 白棋肯定会有 黑棋有可能还没开始下
          black: black[i]?.move || '',
        }
        this.moveHistory.push(list);
      }
      console.log("this.moveHistory", this.moveHistory)
    },
    // 几个跳转的按钮
    jumpToBegin() {
      if (!this.isEnterChild) {
        this.moveNum = -1
        this.learnFen = utils.newGame
      } else {
        this.childMoveNum = -1
        this.childFen = this.tempGameFen
      }
    },
    jumpToBack() {
      if (!this.isEnterChild) {
        this.moveNum--
        if (this.moveNum < 0 ) {
          this.$notify({duration: 1000, title: '通知', message: '已经来到了棋局开始', type: 'warning'})
          this.jumpToBegin()
        }
      } else {
        this.childMoveNum--
        if (this.childMoveNum < 0 ) {
          this.$notify({duration: 1000, title: '通知', message: '已经来到了分支开始', type: 'warning'})
          this.jumpToBegin()
        }
      }
    },
    jumpToNext() {
      if (!this.isEnterChild) {
        if (this.moveNum + 1 >= this.moveList.length) {
          // 没必要做任何操作
          this.$notify({duration: 1000, title: '通知', message: '已经来到了棋局末尾', type: 'warning'})
          return
        }
        this.moveNum ++
      } else {
        if (this.childMoveNum + 1 >= this.childMoveData.length) {
          // 没必要做任何操作
          this.$notify({duration: 1000, title: '通知', message: '已经来到了分支末尾', type: 'warning'})
          return
        }
        this.childMoveNum ++
      }
    },
    jumpToEnd() {
      if (!this.isEnterChild) {
        this.moveNum = this.moveList.length - 1
      } else {
        this.childMoveNum = this.childMoveData.length - 1
      }
    },
    reverseBoard() {
      this.boardColor = this.boardColor === 'white' ? 'black' : 'white';
    },
    // 自动播放
    async autoMove() {
      this.autoLoading = true
      this.jumpToBegin()
      for (let i=1;i<this.moveList.length;i++) {
        await utils.sleep(500)
        this.jumpToNext()
      }
      this.autoLoading = false
    },
    chooseChild(data, index) {
      const btnName = data.btnName
      // 根据状态改编按钮名称和颜色
      this.learnChildData[index].btnName = data.btnName === '选择' ? '返回' : '选择'
      this.learnChildData[index].btnType = data.btnName === '选择' ? 'success' : 'warning'
      console.log("data", data)
      if (btnName === '选择') {
        this.isEnterChild = true
        this.tempGameFen = this.learnFen
        this.childMoveData = this.learnChildData[index].data
        this.childMoveNum = 0
        this.tempMoveNum = this.moveNum
        this.learnFen = this.childMoveData[this.childMoveNum].fen
      } else {
        this.isEnterChild = false
        this.moveNum = this.tempMoveNum
        this.learnFen = this.tempGameFen
      }
    },
    back2GameList() {
      this.isLearnGame = false
      this.isEnterChild = false
      this.moveList = []
      this.moveNum = -1
      this.moveHistory = []
      this.learnFen = utils.newGame
    }
  },
  async mounted() {
    await this.getGameList()
    await this.getOpeningSort()
    await this.getOpeningDistinct()
    this.isDev = location.protocol.indexOf('http') !== -1;
    const isHome = await invoke('isHome', null)
    if (isHome === 'true' || isHome === true) {

    } else {
      this.isBoss = this.isDev
    }
  },
  components: {
    chessboard
  },
  watch: {
    // 监控棋局步骤
    moveNum(moveNum) {
      this.learnChildData = []
      if (!this.moveList[moveNum]) return // 棋局末尾 或者开始
      const childData = this.moveList[moveNum].childData
      this.learnFen = this.moveList[moveNum].fen
      clipboard.writeText(this.learnFen)
      this.currentDescription = this.moveList[this.moveNum].description

      if (childData && childData.length) {
        for (const item of childData) {
          const data = item.data
          let text = ''
          console.log("data", data)
          // 分支是从上一步开始 有多个走法，于是这里要取上一步的fen或者是棋局开始
          let lastFen = this.moveList[moveNum - 1].fen || utils.newGame
          for (const i of data) {
            text += i.move + ' '
            i.fen = chessmate.move(lastFen, i.move)
            lastFen = i.fen
          }
          this.learnChildData.push({
            text,
            data,
            btnName: '选择',
            btnType: 'success',
          })
        }
      }
    },
    childMoveNum(moveNum) {
      if(!this.childMoveData[moveNum]) return // 分支的末尾或者开头
      this.learnFen = this.childMoveData[moveNum].fen
      clipboard.writeText(this.learnFen)
      this.currentDescription = this.childMoveData[moveNum].description
    },
    async searchOpening(searchOpening) {
      await this.getGameList(searchOpening)
    },
  }
}
</script>


<style scoped>
.firstLine {
  display: inline-block;
  margin: 5px;
}
.textarea:deep(.el-textarea__inner) {
  outline: none;
  border: none;
  resize: none;
  box-shadow: none;
}
</style>